/*
Copyright (c) 2008, Mike Gashler

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#include "GSpinLock.h"
#include <time.h>

GSpinLock::GSpinLock()
{
	m_dwLocked = 0;
#ifndef WIN32
	pthread_mutex_init(&m_mutex, NULL);
#endif
#ifdef _DEBUG
	m_szWhoHoldsTheLock = "<Never Been Locked>";
#endif
}

GSpinLock::~GSpinLock()
{
#ifndef WIN32
	pthread_mutex_destroy(&m_mutex);
#endif
}

#ifdef WIN32
static inline unsigned int testAndSet(unsigned int* pDWord)
{
	unsigned int dwRetVal;
	__asm
	{
		mov edx, pDWord
		mov eax, 1
		lock xchg eax, [edx] // This is the line that does the job
			mov dwRetVal, eax
	}
	return dwRetVal;
}
#endif // WIN32

void GSpinLock::Lock(const char* szWhoHoldsTheLock)
{
#ifdef WIN32
	while(testAndSet(&m_dwLocked))
#else
	while(0!=pthread_mutex_trylock(&m_mutex))
#endif
	{
		GSpinLock::sleep(0);
	}
#ifndef WIN32
	m_dwLocked = 1;
#endif
#ifdef _DEBUG
	m_szWhoHoldsTheLock = szWhoHoldsTheLock;
#endif // _DEBUG
}

void GSpinLock::Unlock()
{
#ifdef _DEBUG
	m_szWhoHoldsTheLock = "<Not Locked>";
#endif // _DEBUG
	m_dwLocked = 0;
#ifndef WIN32
	pthread_mutex_unlock(&m_mutex);
#endif
}

HANDLE GSpinLock::SpawnThread(unsigned int (*pFunc)(void*), void* pData)
{
#ifdef WIN32
	unsigned int nID;
	HANDLE hThread = (void*)CreateThread/*_beginthreadex*/(
							NULL,
							0,
							(LPTHREAD_START_ROUTINE)pFunc,
							pData,
							0,
							(unsigned long*)&nID
							);
	if(hThread == BAD_HANDLE)
		ThrowError("Failed to create thread");
	return hThread;
#else // WIN32
	pthread_t thread;
	if(pthread_create(&thread, NULL, (void*(*)(void*))pFunc, pData) != 0)
	{
		ThrowError("Failed to create thread");
	}
	return (HANDLE)NULL;
#endif // else WIN32
}

